const sequelize = require('../config/database');
const { NotFoundError } = require('../utils/errors');
const { Comment } = require('../models/index');

/**
 * 视频控制器
 * 按照新的接口规范实现所有视频相关接口
 */
class VideoController {
  /**
   * 1. 获取视频详情，从视图videos_detail中获取，video_id是主键
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   * @param {Function} next - Express下一个中间件
   */
  static async getVideoDetail(req, res, next) {
    try {
      const { id } = req.params;

      // 使用videos_detail视图查询视频详情
      const video = await sequelize.query(
        'SELECT * FROM videos_detail WHERE id = ?',
        {
          replacements: [id],
          type: sequelize.QueryTypes.SELECT
        }
      );

      if (!video || video.length === 0) {
        throw new NotFoundError('视频不存在');
      }

      // 返回结果
      res.json({
        success: true,
        data: { video: video[0] }
      });
    } catch (error) {
      if (error instanceof NotFoundError) {
        return res.status(404).json({ success: false, message: error.message });
      }
      console.error('获取视频详情失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }



  /**
   * 4. 按照category_id获取所有视频，从视图videos_detail中获取，分页，每页10个
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getVideosByCategory(req, res) {
    try {
      const { category_id } = req.params;
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 直接在videos_detail视图中按category_id过滤
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE category_id = :category_id
         AND deleted_at IS NULL
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { category_id, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        `SELECT COUNT(*) as count FROM videos_detail 
         WHERE category_id = :category_id
         AND deleted_at IS NULL`,
        { replacements: { category_id } }
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('按分类获取视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 5. 按照type_id获取所有视频，从视图videos_detail中获取，分页，每页10个
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getVideosByType(req, res) {
    try {
      const { type_id } = req.params;
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询指定类型的视频
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE video_type_id = :type_id AND deleted_at IS NULL
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { type_id, limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE video_type_id = :type_id AND deleted_at IS NULL',
        { replacements: { type_id } }
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('按类型获取视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }





  /**
   * 11. 获取推荐视频，从视图videos_detail中获取，按照收藏量，分页，每页10个，video_id是主键
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getRecommendedVideos(req, res) {
    try {
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询推荐视频，按照创建时间排序
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE deleted_at IS NULL
         ORDER BY collect_count DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE deleted_at IS NULL'
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取推荐视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 12. 获取热门视频，从视图videos_detail中获取，按照点赞量，分页，每页10个，video_id是主键
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getHotVideos(req, res) {
    try {
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询热门视频，按照点赞量排序
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE deleted_at IS NULL
         ORDER BY like_count DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE deleted_at IS NULL'
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取热门视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 13. 获取精选视频，从视图videos_detail中获取，按照评论量，分页，每页10个，video_id是主键
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getFeaturedVideos(req, res) {
    try {
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询精选视频，按照评论量排序
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE deleted_at IS NULL
         ORDER BY coin_count DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE deleted_at IS NULL'
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取精选视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 14. 获取所有最新视频，从视图videos_detail中获取，分页，每页10个，video_id是主键
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async getAllLatestVideos(req, res) {
    try {
      const { page = 1, limit = 10 } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(limit);
      
      // 使用videos_detail视图查询最新视频
      const results = await sequelize.query(
        `SELECT * FROM videos_detail 
         WHERE deleted_at IS NULL
         ORDER BY created_at DESC
         LIMIT :limit OFFSET :offset`,
        {
          replacements: { limit: parseInt(limit), offset },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      // 获取总数
      const [[{ count }]] = await sequelize.query(
        'SELECT COUNT(*) as count FROM videos_detail WHERE deleted_at IS NULL'
      );
      
      res.json({
        success: true,
        data: {
          videos: results,
          pagination: {
            total: count,
            page: parseInt(page),
            limit: parseInt(limit),
            totalPages: Math.ceil(count / limit)
          }
        }
      });
    } catch (error) {
      console.error('获取最新视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 发布新视频
   * @param {Object} req - Express请求对象，包含视频信息和用户ID
   * @param {Object} res - Express响应对象
   */
  /**
   * 发布新视频
   * @param {Object} req - Express请求对象
   * @param {Object} res - Express响应对象
   */
  static async createVideo(req, res) {
    try {
      // 解析请求参数
      const { title, description, video_url, cover_url, duration, category_id, video_type_id, tags } = req.body;
      // 从认证用户中获取用户ID
      const userId = req.user.id || req.user.userId; // 支持不同的用户ID属性名
      
      // 调试日志 - 检查参数值
      console.log('视频发布参数检查:', {
        title: typeof title, 
        description: typeof description, 
        video_url: typeof video_url,
        cover_url: typeof cover_url,
        duration: typeof duration,
        category_id: typeof category_id,
        video_type_id: typeof video_type_id,
        userId: typeof userId,
        hasAllParams: title && description && video_url && cover_url && duration && category_id && video_type_id && userId
      });
      
      if (!userId) {
        return res.status(401).json({ success: false, message: '用户未认证' });
      }
      
      // 开启数据库事务
      const transaction = await sequelize.transaction();
      
      try {
        // 创建视频记录 - 使用MySQL兼容语法
        await sequelize.query(
          `INSERT INTO videos (title, description, video_url, cover_url, duration, category_id, video_type_id, user_id, created_at, updated_at)
           VALUES (:title, :description, :video_url, :cover_url, :duration, :category_id, :video_type_id, :userId, NOW(), NOW())`,
          {
            replacements: {
              title,
              description,
              video_url,
              cover_url,
              duration,
              category_id,
              video_type_id,
              userId
            },
            transaction
          }
        );
        
        // 在MySQL中获取最后插入的ID
        const [lastIdResult] = await sequelize.query(
          'SELECT LAST_INSERT_ID() as id',
          {
            transaction,
            type: sequelize.QueryTypes.SELECT
          }
        );
        
        const videoId = lastIdResult.id;
        
        // 暂时跳过标签处理，因为video_tag表不存在
        // 后续可以根据实际数据库架构进行调整
        if (tags && Array.isArray(tags) && tags.length > 0) {
          console.log('标签处理已跳过，需要在数据库中创建video_tag表后再实现');
        }
        
        // 提交事务
        await transaction.commit();
        
        // 重新查询创建的视频详情（从视图中获取）
        const [newVideo] = await sequelize.query(
          'SELECT * FROM videos_detail WHERE id = ?',
          {
            replacements: [videoId],
            type: sequelize.QueryTypes.SELECT
          }
        );
        
        // 返回成功响应
        res.status(201).json({
          success: true,
          message: '视频发布成功',
          data: { video: newVideo }
        });
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        console.error('事务处理失败:', error);
        throw error;
      }
    } catch (error) {
      console.error('发布视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 更新视频信息
   * @param {Object} req - Express请求对象，包含视频ID和更新信息
   * @param {Object} res - Express响应对象
   */
  static async updateVideo(req, res) {
    try {
      const { id } = req.params;
      const { title, description, cover_url, category_id, video_type_id, tags } = req.body;
      const userId = req.user.id || req.user.userId; // 支持不同的用户ID属性名
      
      // 检查视频是否存在且属于当前用户
      const [video] = await sequelize.query(
        'SELECT * FROM videos WHERE id = :id AND user_id = :user_id',
        {
          replacements: { id, user_id: userId },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在或无权限操作' });
      }
      
      // 构建更新字段
      const updates = [];
      const replacements = { id };
      
      if (title !== undefined) { updates.push('title = :title'); replacements.title = title; }
      if (description !== undefined) { updates.push('description = :description'); replacements.description = description; }
      if (cover_url !== undefined) { updates.push('cover_url = :cover_url'); replacements.cover_url = cover_url; }
      if (category_id !== undefined) { updates.push('category_id = :category_id'); replacements.category_id = category_id; }
      if (video_type_id !== undefined) { updates.push('video_type_id = :video_type_id'); replacements.video_type_id = video_type_id; }
      
      updates.push('updated_at = NOW()');
      
      // 开启事务
      const transaction = await sequelize.transaction();
      
      try {
        // 更新视频信息
        await sequelize.query(
          `UPDATE videos SET ${updates.join(', ')} WHERE id = :id`,
          {
            replacements,
            transaction
          }
        );
        
        // 处理标签更新（如果有）
        if (tags !== undefined) {
          // 暂时跳过标签处理，因为video_tag表不存在
          // 后续可以根据实际数据库架构进行调整
          console.log('标签处理被跳过');
          /*
          // 删除旧标签关联
          await sequelize.query(
            'DELETE FROM video_tag WHERE video_id = :id',
            { replacements: { id }, transaction }
          );
          
          // 添加新标签关联
          if (tags.length > 0) {
            const tagValues = tags.map(tag => `(:id, :tag, NOW(), NOW())`);
            await sequelize.query(
              `INSERT INTO video_tag (video_id, tag_id, created_at, updated_at) VALUES ${tagValues.join(', ')}`,
              { replacements: { id, tag: tags }, transaction }
            );
          }
          */
        }
        
        // 提交事务
        await transaction.commit();
        
        // 查询更新后的视频详情
        const [updatedVideo] = await sequelize.query(
          'SELECT * FROM videos_detail WHERE id = :id',
          {
            replacements: { id },
            type: sequelize.QueryTypes.SELECT
          }
        );
        
        res.json({
          success: true,
          message: '视频更新成功',
          data: { video: updatedVideo }
        });
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        throw error;
      }
    } catch (error) {
      console.error('更新视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }

  /**
   * 删除视频
   * @param {Object} req - Express请求对象，包含视频ID
   * @param {Object} res - Express响应对象
   */
  static async deleteVideo(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id || req.user.userId; // 支持不同的用户ID属性名
      
      // 检查视频是否存在且属于当前用户
      const [video] = await sequelize.query(
        'SELECT * FROM videos WHERE id = :id AND user_id = :user_id',
        {
          replacements: { id, user_id: userId },
          type: sequelize.QueryTypes.SELECT
        }
      );
      
      if (!video) {
        return res.status(404).json({ success: false, message: '视频不存在或无权限操作' });
      }
      
      // 开启事务
      const transaction = await sequelize.transaction();
      
      try {
        // 软删除视频
        await sequelize.query(
          'UPDATE videos SET deleted_at = NOW() WHERE id = :id',
          {
            replacements: { id },
            transaction
          }
        );
        
        // 暂时跳过标签删除，因为video_tag表不存在
        console.log('标签删除被跳过');
        /*
        // 删除相关标签关联
        await sequelize.query(
          'DELETE FROM video_tag WHERE video_id = :id',
          {
            replacements: { id },
            transaction
          }
        );
        */
        
        // 提交事务
        await transaction.commit();
        
        res.json({
          success: true,
          message: '视频删除成功'
        });
      } catch (error) {
        // 回滚事务
        await transaction.rollback();
        throw error;
      }
    } catch (error) {
      console.error('删除视频失败:', error);
      res.status(500).json({ success: false, message: '服务器错误', error: error.message });
    }
  }
}

module.exports = VideoController;